//
//  YWUploadFailedRecordTableViewController.m
//  maintain
//
//  Created by kyo on 17/1/9.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWUploadFailedRecordTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWConst.h"
#import "NSDate+Additions.h"
#import "WMHttpTool.h"

#import "YWContactHeadFooterView.h"

#import "YWUploadFailedItem.h"
#import "YWUploadFailedRecordCell.h"

#import "YWMission.h"
#import "YWPatrolPointRecord.h"
#import "YWInspectionEquipmentRecord.h"
#import "YWEquipmentMaintenanceRecord.h"
#import "YWEquipmentTroubleRecord.h"
#import "YWMeterReadingRecord.h"
#import "YWAttendanceRecord.h"
#import "YWTroubleMissionModel.h"
#import "YWReportTroubleModel.h"

#import "YWMissionManager.h"
#import "YWDetectAndUpkeepManager.h"
#import "YWKeepWatchMissionManager.h"
#import "YWInspectionMissionManager.h"
#import "YWMeterReadingManager.h"
#import "YWAttendanceManager.h"
#import "YWTroubleMissionManager.h"
#import "YWReportTroubleManager.h"

#import "YWTemTroubleDetailTableViewController.h"
#import "YWCirculationDetailViewController.h"
#import "YWInspecEquipmentRecordDetailTableViewController.h"
#import "YWInspecLocationRecordDetailTableViewController.h"
#import "YWMaintenanceRecordDetailTableViewController.h"
#import "YWKeepWatchLocationRecordDetailTableViewController.h"
#import "YWMeterReadingDetailRecordTableViewController.h"
#import "YWAttendanceRecordDetailTableViewController.h"

#define KHeadViewBaseTag 300
@interface YWUploadFailedRecordTableViewController ()<YWContactHeadFooterViewDelegate>

@end

@implementation YWUploadFailedRecordTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"recordsOfUploading", nil);//@"待上传的记录";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.rowHeight = 60.0f;
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"startUpload", nil) style:UIBarButtonItemStylePlain target:self action:@selector(clickStratUploadEvent:)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - dataSource and delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    YWUploadFailedItem *item = self.dataSource[section];
    NSInteger count = item.isOpen ? item.itemArray.count : 0;
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YWUploadFailedRecordCell *cell = [YWUploadFailedRecordCell cellWithTableView:tableView];
    YWUploadFailedItem *item = self.dataSource[indexPath.section];
    cell.recordObject = item.itemArray[indexPath.row];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    YWContactHeadFooterView *headView = [YWContactHeadFooterView headerWithTableView:tableView];
    
    headView.delegate = self;
    headView.uploadFailedItem = self.dataSource[section];
    headView.tag = KHeadViewBaseTag + section;
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40.0f;
}

#pragma mark - private method
- (void)clickHeaderView:(YWContactHeadFooterView *)headerView{
    NSInteger tag = headerView.tag - KHeadViewBaseTag;
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:tag] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YWUploadFailedItem *item = self.dataSource[indexPath.section];
    id recordObject = item.itemArray[indexPath.row];
    if ([recordObject isKindOfClass:[YWReportTroubleModel class]]) {
        YWReportTroubleModel*reportTrouble = (YWReportTroubleModel*)recordObject;
        YWCirculationDetailViewController *circulationVC = [[YWCirculationDetailViewController alloc] init];
        circulationVC.isNotShowHandleButton = YES;
        circulationVC.troubleMissionModel = reportTrouble.troubleMission;
        [self.navigationController pushViewController:circulationVC animated:YES];
    }else if ([recordObject isKindOfClass:[YWPatrolPointRecord class]]){
        YWPatrolPointRecord *pointRecord = (YWPatrolPointRecord*)recordObject;
        YWKeepWatchLocationRecordDetailTableViewController *recordDetailVC = [[YWKeepWatchLocationRecordDetailTableViewController alloc] init];
        recordDetailVC.patrolPointRecord = pointRecord;
        [self.navigationController pushViewController:recordDetailVC animated:YES];
    }else if ([recordObject isKindOfClass:[YWInspectionEquipmentRecord class]]){
        YWInspectionEquipmentRecord *inspectionRecord = (YWInspectionEquipmentRecord*)recordObject;
        if (inspectionRecord.recordType == YWInspectionEquipmentRecordTypeEquipment && inspectionRecord.equipment) {
            YWInspecEquipmentRecordDetailTableViewController *equipmentDetailRecordVC = [[YWInspecEquipmentRecordDetailTableViewController alloc] init];
            equipmentDetailRecordVC.inspectionEquipmentRecord = inspectionRecord;
            [self.navigationController pushViewController:equipmentDetailRecordVC animated:YES];
        }else{
            YWInspecLocationRecordDetailTableViewController *locationRecordVC = [[YWInspecLocationRecordDetailTableViewController alloc] init];
            locationRecordVC.inspectionEquipmentRecord = inspectionRecord;
            [self.navigationController pushViewController:locationRecordVC animated:YES];
        }
    }else if ([recordObject isKindOfClass:[YWEquipmentTroubleRecord class]]){
        YWEquipmentTroubleRecord *trobleRecord = (YWEquipmentTroubleRecord*)recordObject;
        YWTroubleMissionModel* troubleMission = [[YWTroubleMissionManager shareManager] troubleMissionModelWithTroubleId:trobleRecord.missionId];
        if (troubleMission) {
            if (troubleMission.trouble.troubleId<=0 && troubleMission.troubleStatus == YWTroubleMissionStatusFinish) {
                YWTemTroubleDetailTableViewController *tempTroubleVC = [[YWTemTroubleDetailTableViewController alloc] init];
                tempTroubleVC.troubleMissionModel = troubleMission;
                [self.navigationController pushViewController:tempTroubleVC animated:YES];
            }else{
                YWCirculationDetailViewController *circulationVC = [[YWCirculationDetailViewController alloc] init];
                circulationVC.isNotShowHandleButton = YES;
                circulationVC.troubleMissionModel = troubleMission;
                [self.navigationController pushViewController:circulationVC animated:YES];
            }
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionNotFound", nil)];
        }
        
    }else if ([recordObject isKindOfClass:[YWEquipmentMaintenanceRecord class]]){
        YWEquipmentMaintenanceRecord *maintenanceRecord = (YWEquipmentMaintenanceRecord*)recordObject;
        YWMaintenanceRecordDetailTableViewController* maintenanceVC = [[YWMaintenanceRecordDetailTableViewController alloc] init];
        maintenanceVC.maintenanceRecord = maintenanceRecord;
        [self.navigationController pushViewController:maintenanceVC animated:YES];
    }else if ([recordObject isKindOfClass:[YWMeterReadingRecord class]]){
        YWMeterReadingRecord *meterReadingRecord = (YWMeterReadingRecord*)recordObject;
        YWMeterReadingDetailRecordTableViewController* detailVC = [[YWMeterReadingDetailRecordTableViewController alloc] init];
        detailVC.meterReadingRecord = meterReadingRecord;
        [self.navigationController pushViewController:detailVC animated:YES];
    }else if ([recordObject isKindOfClass:[YWAttendanceRecord class]]){
        YWAttendanceRecord *attendanceRecord = (YWAttendanceRecord*)recordObject;
        YWAttendanceRecordDetailTableViewController* attendanceRecordVC = [[YWAttendanceRecordDetailTableViewController alloc] init];
        attendanceRecordVC.attendanceRecord = attendanceRecord;
        [self.navigationController pushViewController:attendanceRecordVC animated:YES];
    }
    
}

- (void)clickStratUploadEvent:(id)sender{
    //手动点击，触发离线上传
    if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
        if ([[WMHttpTool shareHttpTool] networkType] == WMNetworkTypeWiFi) {
            [self startUpload];
        }else{
            UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"networkIsNotWifiAndSureToUpload", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertController animated:YES completion:nil];
            [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
            [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self startUpload];
            }]];
        }
    }else{
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
    }
}
- (void)startUpload{
    self.navigationItem.rightBarButtonItem.enabled = NO;
    [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"allRecordIsUploading", nil)];
    
    NSString *key = @"KUploadFailedRecordUserDefaultsKey";
    NSDate *currtentTime = [NSDate date];
    NSDate *lastUploadTime = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    NSInteger interval = [currtentTime minutesAfterDate:lastUploadTime];
    if (lastUploadTime != nil && interval < 1) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"uploading", nil)];
        return;
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:currtentTime forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        //检测，保养
        [[YWDetectAndUpkeepManager new] uploadFailedDetectAndUpkeepRecords];
        //报障
        [[YWReportTroubleManager shareManager] startUnUploadReportTrouble];
        //维修
        [[YWTroubleMissionManager shareManager] startUnUploadTroubleMissionRecord];

        //巡更
        [[YWKeepWatchMissionManager shareManager] uploadFailPatrolPointRecords];
        //巡查
        [[YWInspectionMissionManager shareManager] uploadFailInspectionRecords];
        //抄表
        [[YWMeterReadingManager shareManager] uploadFailMeterReadingRecords];
        //签到（签到改成在线的）
//        [[YWAttendanceManager shareManager] uploadFailAttendanceInfo];
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
    
    
}
@end
